package org.example.daodemo;

import java.sql.*;
import java.util.Collection;

public class DBTest {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/library_management?allowPublicRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
        String username = "root"; // 你的数据库用户名
        String password = "123456"; // 你的数据库密码

        Connection conn = null; // 声明一个Connection对象
        PreparedStatement prep =null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,username,password);
            System.out.println("数据库连接成功！连接对象: " + conn);

            // 你的数据库操作代码
          String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
          prep = conn.prepareStatement(sql);
          prep.setString(1, "admin");
          prep.setString(2, "admin123");
          resultSet = prep.executeQuery();

          while (resultSet.next()) {
              System.out.println("User ID: " + resultSet.getInt("id"));
              System.out.println("Username: " + resultSet.getString("username"));
              System.out.println("Password: " + resultSet.getString("password"));
              System.out.println("Email: " + resultSet.getString("email"));
          }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 关闭连接 (见下文)
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (prep != null) {
                try {
                    prep.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
